package net.esj.basic.core.business.provider.redundant;

import java.util.HashSet;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.log4j.Logger;

import net.esj.basic.pojo.MObject;
import net.esj.basic.pojo.MObjectVo;
import net.esj.basic.core.utils.MObjectSet;

public class RedundantFactory {
	
	private static final long PERIOD_TIME = 5*60*1000;
	
	private static Logger logger = Logger.getLogger(RedundantFactory.class);
	
	private static RedundantFactory _instance;

	private Set<RedundantInterface> redundantInterfaces = new HashSet<RedundantInterface>();
	
	private MObjectSet cache = new MObjectSet();
	
	private Timer timer;
	
	private TimerTask task;
	
	private RedundantFactory() {
		super();
		timer = new Timer(true);
		task = new TimerTask() {
			
			@Override
			public void run() {
				try {
					doRedundant();
				} catch (CloneNotSupportedException e) {
					e.printStackTrace();
				}
			}
		};
		timer.scheduleAtFixedRate(task, 10000, PERIOD_TIME);
	}

	public void registry(RedundantInterface intf){
		redundantInterfaces.add(intf);
	}
	
	public void doRedundant(MObject mObject){
		MObjectVo vo = new MObjectVo();
		vo.setId(mObject.getId().toString());
		vo.setMType(mObject.getMType());
		vo.setName(mObject.getName());
		cache.add(vo);
	}
	
	private void doRedundant() throws CloneNotSupportedException{
		logger.debug("执行冗余检测!");
		MObjectSet set ;
		synchronized(this){
			set = (MObjectSet) cache.clone();
			cache.clear();
		}
		logger.debug("该次共有需处理冗余对象:"+set.size()+"个");
		for(RedundantInterface intf:redundantInterfaces){
			for(MObject mObject:set){
				if(intf.checkMType(mObject)){
					try{
						intf.doRedundant(mObject);
					}catch(Throwable e){}
				}
			}
		}
	}
	
	public static RedundantFactory getInstance(){
		if(_instance==null){
			_instance = new RedundantFactory();
		}
		return _instance;
	}
}
